<template>
  <div class="pending">
    <!-- 搜索 -->
    <div class="formSearch">
      <el-form
        :inline="true"
        :model="query"
      >
        <el-form-item label="商品名称">
          <el-input
            v-model.trim="query.search"
            maxlength="20"
            placeholder="请输入商品名称"
          />
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select
            v-model="query.shelveState"
            placeholder="请选择上架状态"
          >
            <el-option label="全部" value="null" />
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
            <el-option label="待审核" value="2" />
            <el-option label="审核失败" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="官方分类">
          <ClassifySelect v-model="query.classifyId" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="handleSearch">查询</el-button>
          <el-button plain @click="clear">重置</el-button>
        </el-form-item>
        <el-form-item style="display: block; width: 100%;">
          <el-button type="success" plain @click="handleCreate('create')">新增商品</el-button>
          <el-button type="success" plain @click="sends">批量导入</el-button>
          <el-button
            type="success"
            plain
            @click="productDataExport"
          >导出商品</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      :header-cell-style="{
        background: '#EEF3FF',
        color: '#333333'
      }"
      tooltip-effect="dark"
      style="width: 100%"
      class="dataTable"
    >
      <el-table-column
        prop="productId"
        label="商品id"
        show-overflow-tooltip
      />
      <el-table-column label="商品主图" width="150" align="center">
        <template #default="scope">
          <img
            height="80"
            width="80"
            :src="scope.row.productImage"
            alt
            srcset
          />
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="商品名称" width="220" />
      <el-table-column
        prop="section"
        label="售价区间"
        show-overflow-tooltip
        width="140"
      />
      <el-table-column
        prop="memberSection"
        label="会员价"
        show-overflow-tooltip
        width="140"
      />
      <el-table-column
        prop="ifCredit"
        label="积分兑换"
        show-overflow-tooltip
        width="100"
      >
        <template #default="scope">
          <span v-if="scope.row.ifCredit == 1">允许</span>
          <span v-if="scope.row.ifCredit == 0">不允许</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="stockNumber"
        label="库存"
        show-overflow-tooltip
      />
      <el-table-column prop="volume" label="销量" show-overflow-tooltip />
      <el-table-column prop="volume" label="上架状态" show-overflow-tooltip width="100">
        <template #default="scope">
          <span v-if="scope.row.shelveState == 0">未上架</span>
          <span v-if="scope.row.shelveState == 1">已上架</span>
          <span v-if="scope.row.shelveState == 2">待审核</span>
          <span v-if="scope.row.shelveState == 3">审核失败</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="reject"
        label="驳回原因"
        show-overflow-tooltip
        width="100"
      />
      <el-table-column
        :formatter="(row) => getBrandName(row)"
        label="品牌"
        show-overflow-tooltip
      />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="edit(scope.row, 'edit')">编辑</el-button>
          <el-button
            v-if="[0,3].includes(scope.row.shelveState)"
            type="primary"
            link
            @click="down(scope.row)"
          >{{scope.row.shelveState === 0?'上架':'重新上架'}}</el-button>
          <el-popconfirm
              v-if="scope.row.shelveState == 1"
              title="确认下架？"
              @confirm="down(scope.row)"
          >
            <template #reference>
              <el-button type="primary" link>下架</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm
            v-if="scope.row.shelveState !== 1"
            title="确认删除？"
            @confirm="del(scope.row)"
          >
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      background
      :total="page.total"
      style="margin: 20px 0 0 0;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 批量导入 -->
    <el-dialog
      v-model="visible.productImport"
      title="批量导入商品"
      :close-on-click-modal="false"
      center
      width="400px"
    >
      <div class="uploadDialog">
        <el-upload
          drag
          :limit="uploadSetting.limit"
          :auto-upload="uploadSetting.isAutoUpload"
          :accept="uploadSetting.accept"
          :headers="uploadSetting.headers"
          :action="uploadUrl"
          :before-upload="beforeUploadFile"
          :on-change="fileChange"
          :on-remove="batchRemove"
          :on-exceed="exceedFile"
          :on-success="handleSuccess"
          :on-error="handleError"
          :file-list="batchFileList"
        >
          <el-icon><el-icon-upload /></el-icon>
          <div class="el-upload__text">
            <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传xlsx文件，且不超过10M
            </div>
            <div class="el-upload__tip">
              上传前不知道excel模板的，请点击
              <span class="clickMe" @click="poDownload">点我下载模板</span> 去下载
            </div>
          </template>
        </el-upload>
        <br />
        <el-button
          size="small"
          type="primary"
          @click="uploadFile"
        >立即上传</el-button>
      </div>
    </el-dialog>
    <!-- 新增/修改商品弹窗 -->
    <el-dialog
      v-model="visible.commidy"
      :title="btnType !== 'edit' ? '新增商品' : '编辑商品'"
      width="74%"
      center
      top="10vh"
      :close-on-click-modal="false"
      @close="closeModal"
    >
      <CommAdd
        ref="commFormRef"
        :product-id="currentProduct.productId"
        @cancel="cancelForm"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { Upload as ElIconUpload } from '@element-plus/icons-vue'
import CommAdd from '@/views/commodity/commoditySystem/addCommodity.vue'
import ClassifySelect from '@/components/commodity/classifySelect.vue'
import { getToken } from '@/utils/auth'
import {
  getClassifyGetAll,
  getClassifyDelete,
  getClassifyStart,
  downloadTemplate,
  importProduct,
  getClassify,
  productExport,
  getBrandList
} from '@/api/commodity'
import { uploadUrl } from '@/utils/request'
import { nextTick, onMounted, reactive, ref } from 'vue'

function getBrandName (row) {
  const find = brandList.value.find(item =>
    item.id === row && row.brandId
  )
  return find ? find.brandName : '-'
}

const commFormRef = ref();
const btnType = ref();

let visible = reactive({
  vipPrice: false,
  productImport: false,
  commidy: false,
})

let page = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

/**
 * @property {string} search 搜索字段
 * @property {string} shelveState 上架状态 1-上架 0-不上架 null-全部
 * @property {} stock 库存状态 1-有库存 0-无库存 null-全部
 * @property {} classifyId 最下级分类id
 */
let query = reactive({
  search: '',
  shelveState: '',
  // stock: '',
  classifyId: null,
})

let tableData = ref([]);
// 初始化查询所有数据
function getAll () {
  getClassifyGetAll(Object.assign(
    {},
    page,
    query
  )).then(res => {
    tableData.value = res.data.list
    page.total = res.data.total
  })
}

let brandList = ref([]);
function getBrandListData () {
  getBrandList().then(res => {
    brandList.value = res.data
  })
}

function cancelForm () {
  closeModal()
  visible.commidy = false
  clear()
  getAll()
}
function closeModal () {
  commFormRef.value?.reset()
}
function handleSizeChange (val) {
  page.pageSize = val
  getAll()
}
function handleCurrentChange (val) {
  page.page = val
  getAll()
}
//  查询
function handleSearch () {
  page.page = 1
  getAll()
}
// 重置
function clear () {
  query.classifyId = null
  query.search = ''
  query.shelveState = ''
  page.page = 1
  getAll()
}

let currentProduct = reactive({
  productId: null
})
// 新增商品
function handleCreate (type) {
  btnType.value = type
  currentProduct.productId = null
  visible.commidy = true
}

// 导出商品
function productDataExport () {
  ElMessage.success('数据导出中，请勿重复操作！')
  productExport(Object.assign({}, page, query)).then(res => {
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const fileName = '商品数据明细表.xls'
    if ('download' in document.createElement('a')) {
      // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.href = URL.createObjectURL(blob)
      elink.style.display = 'none'
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}

/**
 * **********************
 * ************** 商品导入
 * **********************
 */
let uploadSetting = reactive({
  limit: 1,
  isAutoUpload: false,
  headers: {
    'Authorization': getToken(),
  },
  accept: '.xlsx'
})
let batchFileList = ref([]);
// 批量导入
function sends () {
  visible.productImport = true
  batchFileList.value = []
}
// 编辑商品
function edit (row, type) {
  btnType.value = type
  visible.commidy = true
  currentProduct.productId = row.productId
  nextTick(() => {
    commFormRef.value.details(type)
  })
}

// 删除商品
function del (row) {
  ElMessageBox.confirm('选中数据将被永久删除, 是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      getClassifyDelete({
        productId: row.productId
      }).then((res) => {
        if (res.code === '') {
          ElMessage.success('删除成功')
          getAll()
        }
      })
    })
    .catch(() => {})
}
// 商品上下架
function down (row) {
  if (row.shelveState === 1) {
    getClassifyStart({
      productId: row.productId,
      shelveState: 0,
    }).then(res => {
      if (res.code === '') {
        ElMessage.success('下架成功')
        getAll()
      }
    })
  } else {
    getClassifyStart({
      productId: row.productId,
      shelveState: 1,
    }).then(res => {
      if (res.code === '') {
        ElMessage.success('上架成功')
        getAll()
      }
    })
  }
}

// *********************导入部分
// 下载模板
function poDownload () {
  downloadTemplate().then((res) => {
    const blob = new Blob([res])
    const fileName = '批量导入商品模板.xlsx'
    if ('download' in document.createElement('a')) {
      // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}
// 导入
function uploadFile () {
  if (batchFileList.value.length === 0) {
    ElMessage.warning('请上传文件')
  } else {
    const formDate = new FormData()
    formDate.append('file', batchFileList.value[0])
    importProduct(formDate).then((res) => {
      if (res.code === '') {
        ElMessage.success('导入成功')
        visible.productImport = false
        batchFileList.value = []
        getAll()
      }
    })
  }
}
// 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
function beforeUploadFile (file) {
  const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
  const size = file.size / 1024 / 1024
  if (extension !== 'xlsx') {
    ElMessage.warning('只能上传后缀是.xlsx的文件')
  }
  if (size > 10) {
    ElMessage.warning('文件大小不得超过10M')
  }
}
// 文件状态改变时的钩子
function fileChange (_file, _batchFileList) {
  batchFileList.value.push(_file.raw)
}
function batchRemove (_file, _batchFileList) {
  batchFileList.value = []
}
// 文件超出个数限制时的钩子
function exceedFile (_files, _batchFileList) {
  ElMessage.warning(`只能选择1个文件`)
}
// 文件上传成功时的钩子
function handleSuccess (_res, _file, _batchFileList) {
  ElMessage.success('文件上传成功')
}
// 文件上传失败时的钩子
function handleError () {
  ElMessage.error('文件上传失败')
}

onMounted(() => {
  getBrandListData()
  getAll()
})
</script>

<style lang="scss" scoped>
.pending {
  padding: 20px;
  margin-top: 20px;
  background-color: #FFFFFF;
}
.clickMe {
  color: #3a68f2;
  cursor: pointer;
}
.uploadDialog {
  // display: flex;
  // flex-direction: column;
  // justify-content: center;
  :deep(.el-upload__tip) {
    display: inline-block;
    width: 360px;
    margin: auto;
  }
}
.vipDialog {
  .priceTable {
    table {
      width: 100%;
      text-align: center;
      border-left: 1px solid #ebeef5;
      border-bottom: 1px solid #ebeef5;
      font-size: 14px;
      color: #606266;
      border-collapse: collapse;
      tr {
        border-top: 1px solid #ebeef5;
        th {
          padding: 12px 0;
          background: #eef3ff;
          color: #333;
          border-right: 1px solid #ebeef5;
        }
        td {
          padding: 12px 0;
          border-right: 1px solid #ebeef5;
          &.td-input {
            .el-input {
              width: 80px;
              margin-right: 0;
            }
          }
          &:nth-child(1),
          &:nth-child(2) {
            width: 80px;
          }
          .el-input {
            width: 100px;
            margin-right: 10px;
          }
        }
      }
    }
  }
  .clearBtn {
    margin-top: 20px;
  }
}
.clone {
  a {
    color: #3A68F2;
    cursor: pointer;
  }
  .product-link {
    margin-top: 10px;
    display: flex;
    .title {
      width: 123px;
      text-align: right;
    }
  }
}
:deep(.el-overlay) {
  z-index: 2008 !important;
}

.formSearch{
  .el-select{
    width: 200px;
  }
}
</style>
